$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_bcxy_m")
    const dgrid1 = $NG.getCmpApi("p_form_bcxy_d1")
    const getHeadValue = (str) => mstform.getItem(str).getValue()

    if(page.oType == 'add'){
        setBillNo()
        hiddenHeadKey()
    }

    useValuesChange(()=>{
        setBillNo()
    },"p_form_bcxy_m.u_fbhtbh")

    useValuesChange(()=>{
        hiddenHeadKey()
    },"p_form_bcxy_m.u_sfybg")

    useUpdateRows(({args})=>{
        const rows = args[0]
        let total_amt = 0
        rows.forEach(item=>{
            total_amt += (Number(item.u_hj) || 0)
        })
        mstform.getItem("u_bcxyje").setValue(total_amt)
    },"p_form_bcxy_d1")

    // 获取最新的流水号
    function setBillNo() {
        const phid = mstform.getValues().phid || '0'
        const cnt = mstform.getItem("u_fbhtbh").getValue()
        console.log(`setBillNo`,phid,cnt);
        if ( !cnt) return
        $NG.execServer("SELECT", { sql: `select phid,u_bcxybh from p_form_bcxy_m where u_fbhtbh = '${cnt}' and phid != '${phid}'` }, (res) => {
            if (res.count == 0) {
                 mstform.getItem("u_bcxybh").setValue(mstform.getItem("u_fbhtbh").getText()+"-001")
                return
            }
            const datas = JSON.parse(res.data).reduce((value, item) => {
                value.push(item.extendObjects.u_bcxybh)
                return value
            }, [])
            const maxNum = Math.max(...datas.map(item => {
                const parts = item.split("-");
                return parseInt(parts[parts.length - 1], 10); // 转成数字
            }));
            mstform.getItem("u_bcxybh").setValue(mstform.getItem("u_fbhtbh").getText()+"-"+maxNum +1)
        })
    }

    // 隐藏表头字段
    function hiddenHeadKey(){
        const u_sfybg = getHeadValue("u_sfybg")
        const keys = ["u_xfbsmc","u_khhmc","u_yhzh","u_hh",]
        let hidden = true
        if(u_sfybg == '01'){
          hidden = false  
        } 
        keys.forEach(el=>{
            mstform.getItem(el).setProps({
                hidden
            })
        })
    }
})    